package com.neu.api.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.neu.api.constan.BookConst;
import com.neu.api.mapper.BookMapper;
import com.neu.api.pojo.Book;
import com.neu.api.query.BookQuery;
import com.neu.api.service.BookService;
import com.neu.api.utils.PageResult;
import com.neu.api.vo.BookListVO;
import com.neu.api.vo.BookVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class BookServiceImpl implements BookService {

    @Resource
    private BookMapper bookMapper;


    @Override
    public PageResult<BookListVO> find(BookQuery bookQuery) {
        //设置是否需要分页
        PageHelper.startPage(bookQuery.getPage(),bookQuery.getPageSize());

        Page<BookListVO> page = (Page<BookListVO>) bookMapper.find(bookQuery);
        PageInfo<BookListVO> pageInfo = page.toPageInfo();


        List<BookListVO> bookListVOList = pageInfo.getList();
        long total = pageInfo.getTotal();

        PageResult<BookListVO> pageResult = new PageResult<>();
        pageResult.setTotal(total);
        pageResult.setList(bookListVOList);

        return pageResult;
    }


    @Override
    public void receive(String num) {
        Book book = new Book();
        book.setNum(num);
        book.setStatus(BookConst.RECEIVED);  //已接单
        bookMapper.update(book);
    }

    @Override
    public void delivery(String num) {
        Book book = new Book();
        book.setNum(num);
        book.setStatus(BookConst.DELIVERING); //派送中
        bookMapper.update(book);
    }

    @Override
    public void complete(String num) {
        Book book = new Book();
        book.setNum(num);
        book.setStatus(BookConst.COMPLETED);  //已经完成
        bookMapper.update(book);
    }


    @Override
    public void cancel(String num, String cancelReason) {

        //TODO
        //判断当前订单是否已经支付，如果已经支付则需要退款

        Book book = new Book();
        book.setNum(num);
        book.setStatus(BookConst.CANCELLED); //设置已取消状态
        book.setCancelReason(cancelReason);
        book.setCancelTime(new Date());
        bookMapper.update(book);
    }

    @Override
    public void reject(String num, String rejectionReason) {
        //TODO
        //判断当前订单是否已经支付，如果已经支付则需要退款

        Book book = new Book();
        book.setNum(num);
        book.setStatus(BookConst.CANCELLED); //设置已取消状态
        book.setRejectionReason(rejectionReason);
        book.setCancelTime(new Date());

        bookMapper.update(book);
    }

    @Override
    public BookVO findByNum(String num) {
        return bookMapper.findByNum(num);
    }

}
